package com.culture.java.online.education.platform.common.core.listener;

import org.slf4j.MDC;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.GenericApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.ResolvableType;
import org.springframework.core.env.ConfigurableEnvironment;

// 动态设置日志文件名称和路径的监听器
public class MDCLogListener implements GenericApplicationListener {

    /*
       supportsEventType方法如果返回true,则会触发onApplicationEvent方法执行
       这个方法主要判断当前事件是什么事件类型
     */
    @Override
    public boolean supportsEventType(ResolvableType resolvableType) {
        return resolvableType.isAssignableFrom(ApplicationEnvironmentPreparedEvent.class);
    }

    // 一旦发生了相关的事件，就会触发该方法，参数为事件对象
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        // 将应用的名称放入MDC，作为日志的文件名称
        // 获取环境准备事件
        ApplicationEnvironmentPreparedEvent applicationEnvironmentPreparedEvent = (ApplicationEnvironmentPreparedEvent) event;
        // 获取配置的参数
        ConfigurableEnvironment configurableEnvironment = applicationEnvironmentPreparedEvent.getEnvironment();
        // 获取微服务的名称
        String springApplicationName = configurableEnvironment.getProperty("spring.application.name");
        // 设置MDC的值
        MDC.put("springApplicationName", springApplicationName);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 19;
    }

}
